import * as vite from "vite"
import vue from "@vitejs/plugin-vue"
import path from 'path'
import fs from 'fs'
import electron from 'electron'
import esbuild from 'esbuild'
import env from './env.js'
import os from 'os'
import { spawn } from 'child_process'


let dev = {
    server: null,
    serverPort: 5000,
    async createServer() {
        let options = {
            configFile: false,
            server: {
                port: this.serverPort
            },
            plugins: [vue()]
        }

        this.server = await vite.createServer(options)
        await this.server.listen()
    },
    buildMain() {
        let entryFilePath = path.join(process.cwd(), "src/main/app.js")

        let outfile = path.join(process.cwd(), 'release/bundled/entry.cjs')
        let preload = path.join(process.cwd(), "src/preload/preload.js")
        let preloadJs = path.join(process.cwd(), 'release/bundled/preload.js')
        esbuild.buildSync({
            entryPoints: [entryFilePath],
            outfile,
            minify: false,
            bundle: true,
            platform: 'node',
            sourcemap: true,
            external: ['electron']
        })
        esbuild.buildSync({
            entryPoints: [preload],
            outfile: preloadJs,
            minify: false,
            bundle: true,
            platform: 'node',
            sourcemap: true,
            external: ['electron']
        })


        let envScript = this.getEnvScript()
        let js = `${envScript}${os.EOL}${fs.readFileSync(outfile)}`

        fs.writeFileSync(outfile, js)
    },
    getEnvScript() {

        env.WEB_PORT = this.serverPort
        env.RES_DIR = path.join(process.cwd(), 'resource/release')
        let script = ''
        for (let v in env) {
            script += `process.env.${v} = "${env[v]}";`
        }
        return script
    },
    createElectronProcess() {
        this.electronProcess = spawn(
            electron.toString(),
            [path.join(process.cwd(), 'release/bundled/entry.cjs')],
            {
                cwd: process.cwd()
            }

        );
        this.electronProcess.on('close', () => {
            this.server.close()
            process.exit()
        })
        this.electronProcess.stdout.on('data', (data) => {
            data = data.toString()
            console.log(data);
        })
    }

}

dev.createServer()
dev.buildMain()
dev.createElectronProcess()
